import * as types from '../types'


// 该函数是用来获取选中的数量和是否被全选
function selectCountFn (list) {

  const arr = list.filter(item => item.isSelect)

  return {
    selectCount: arr.length,
    isAll: arr.length === list.length
  }
}

const reducer = (state = {
  selectCount: 1, // 已经选中的数量
  isAll: false, // 是否为全选
  todoList: [{
    isSelect: false,
    title: '嗨起来',
    id: 'hsorghoiehroiterioteugi'
  }, {
    isSelect: true,
    title: '干大事',
    id: 'hdsiofhhisofhoiasdadaw'
  }]
}, action) => {

  let obj = null

  switch (action.type) {
    case types.ADD_TODO:
      state.todoList.push(action.payload)
      obj = selectCountFn(state.todoList)

      return { ...state, todoList: [...state.todoList], ...obj }
    case types.UPDATE_TODO:
      // 找到对应元素的索引值
      const index = state.todoList.findIndex(item => item.id === action.payload.id)
      state.todoList.splice(index, 1, action.payload)
      obj = selectCountFn(state.todoList)
      return { ...state, todoList: [...state.todoList], ...obj }

    case types.DEL_TODO:
      // 找到对应元素的索引值
      const index2 = state.todoList.findIndex(item => item.id === action.payload.id)
      state.todoList.splice(index2, 1)
      obj = selectCountFn(state.todoList)
      return { ...state, todoList: [...state.todoList], ...obj }

    case types.SELECT_ALL:

      state.todoList.forEach(item => {
        item.isSelect = action.payload
      })

      obj = selectCountFn(state.todoList)
      return { ...state, todoList: [...state.todoList], ...obj }
    default:
      return state
  }
}

export default reducer
